package com.csun.nusing.ui.familyactivity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ActionBar.LayoutParams;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.csun.nusing.R;
import com.csun.nusing.bean.UrlBean;
import com.csun.nusing.bean.jsonbean.AddOlderJsonBean;
import com.csun.nusing.bean.jsonbean.AdressBaseJsonBean;
import com.csun.nusing.bean.jsonbean.BaseJsonBean;
import com.csun.nusing.bean.jsonbean.FilePostJsonBean;
import com.csun.nusing.bean.jsonbean.SearchOlderInfoJsonBean;
import com.csun.nusing.presenter.CommonPresenter;
import com.csun.nusing.ui.BaseActivity;
import com.csun.nusing.ui.myview.SelectPicPopupWindow;
import com.csun.nusing.util.PhotoUtils;
import com.csun.nusing.util.SPUtils;
import com.csun.nusing.util.TakePictureManager;
import com.csun.nusing.util.ToastUtil;
import com.google.gson.Gson;
import com.home.administrator.okhttplibrary.IOkTaskCallback;
import com.home.administrator.okhttplibrary.OkHttpTask;
import com.home.administrator.okhttplibrary.OkHttpTask.OkHttpTaskBuidler.OkType;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 修改老人 ClassName: FamilyAddOlderActivity
 *
 * @author fzq
 * @Description: TODO
 * @date 2017-11-8
 */
@SuppressLint("Override")
public class FamilyEditOlderActivity extends BaseActivity<CommonPresenter> {

    private ImageView okiv;
    private ImageView headiv;
    private EditText nameet;
    private RelativeLayout sexrl;
    private TextView sextv;
    private EditText phoneet;
    private TextView birdaytv;
    private EditText egnameet;
    private String oldname;
    private String oldphone;
    private String usersex = "0";
    private String egcontact;
    private EditText egphoneet;
    private String egphone;
    private PopupWindow mPopupWindow;
    private View popview;
    private RadioGroup popsexrg;
    private SelectPicPopupWindow menuWindow;
    private String userPicId;
    private String userPic;
    private String oldbirthday = "1930-1-0";
    private Calendar calendar;
    private int year = 1930;
    private int month = 1;
    private int day = 0;
    private OkHttpClient client;
    protected BaseJsonBean baseJsonBean;
    protected Uri imageUri;
    protected File file;
    protected static final int REQUESTCODE_TAKE = 0x1;
    private static final int REQUESTCODE_PICK = 0x2;
    private static final int REQUESTCODE_CUTTING = 0x3;
    protected static final String IMAGE_FILE_NAME = "temphead.jpg";
    public static final MediaType JSON = MediaType
            .parse("application/json; charset=utf-8");
    private String urlpath;
    private String authorization;
    protected FilePostJsonBean bean;
    private static final int CODE_GALLERY_REQUEST = 0xa0;
    private static final int CODE_CAMERA_REQUEST = 0xa1;
    private static final int CODE_RESULT_REQUEST = 0xa2;
    private static final int CAMERA_PERMISSIONS_REQUEST_CODE = 0x03;
    private static final int STORAGE_PERMISSIONS_REQUEST_CODE = 0x04;
    private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/photo.jpg");
    private File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/crop_photo.jpg");
    private Uri cropImageUri;
    private boolean addBedFlag;//添加床位标识符
    private String olderId;
    private String oldbuildname;
    private String oldroomname;
    private String oldBedname;


    @Override
    public int getContentViewId() {
        return R.layout.activity_family_edit_older;
    }

    @Override
    public void initSubViews(View view) {
        super.initSubViews(view);
        initview();
    }

    /**
     * 初始控件
     *
     * @param
     * @return void
     * @throws
     * @Description: TODO
     * @author fzq
     * @date 2017-11-8
     */
    private void initview() {
        okiv = (ImageView) findViewById(R.id.family_edit_older_ok_iv);
        headiv = (ImageView) findViewById(R.id.family_editolder_head_iv);
        nameet = (EditText) findViewById(R.id.editolder_name_et);
        sexrl = (RelativeLayout) findViewById(R.id.family_editolder_sex_rl);
        sextv = (TextView) findViewById(R.id.family_editolder_sex_tv);
        phoneet = (EditText) findViewById(R.id.family_editolder_phone_et);
        birdaytv = (TextView) findViewById(R.id.family_editolder_birday_tv);
        egnameet = (EditText) findViewById(R.id.family_editolder_egname_et);
        egphoneet = (EditText) findViewById(R.id.family_editolder_egphone_et);
        okiv.setOnClickListener(new click());
        birdaytv.setOnClickListener(new click());
        headiv.setOnClickListener(new click());
        sexrl.setOnClickListener(new click());
    }

    private void initSexPop() {
        View popupView = getLayoutInflater().inflate(
                R.layout.layout_popupwindow, null);
        mPopupWindow = new PopupWindow(popupView, LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT, true);
        mPopupWindow.setTouchable(true);
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable(getResources(),
                (Bitmap) null));
        popview = popupView.findViewById(R.id.layout_popwindow_view);
        popview.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopupWindow.dismiss();
            }
        });
        popsexrg = (RadioGroup) popupView
                .findViewById(R.id.nursing_pop_sex_select_rg);
        popsexrg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.nursing_pop_sex_select_one_rb:
                        usersex = "0";
                        sextv.setText(getString(R.string.man));
                        break;
                    case R.id.nursing_pop_sex_select_two_rb:
                        usersex = "1";
                        sextv.setText(getString(R.string.woman));
                        break;
                }
            }
        });
    }

    /**
     * 添加老人
     *
     * @param
     * @return void
     * @throws
     * @Description: TODO
     * @author fzq
     * @date 2017-11-8
     */
    protected void olderAdd() {
        Log.e("fzq", "-----------add");
        oldname = nameet.getText().toString().trim();
        if (oldname == null || oldname.length() < 1) {
            okiv.setEnabled(true);
            ToastUtil.showMessage(this, R.string.old_name_not_empty);
            return;
        }
        oldphone = ""+phoneet.getText().toString().trim();
        egcontact = ""+egnameet.getText().toString().trim();
        egphone = egphoneet.getText().toString().trim();
        if (egphone == null || egphone.length() < 1) {
            okiv.setEnabled(true);
            ToastUtil.showMessage(this, R.string.urgent_phone_not_empty);
            return;
        }
        if (userPicId == null || userPicId.length() < 1) {
            okiv.setEnabled(true);
            ToastUtil.showMessage(this, R.string.please_send_pic);
            return;
        }
        if (egcontact == null || egcontact.length() < 1) {
            okiv.setEnabled(true);
            ToastUtil.showMessage(this, R.string.please_send_ecg_name);
            return;
        }
        if (oldphone == null || oldphone.length() < 2) {
            okiv.setEnabled(true);
            ToastUtil.showMessage(this, R.string.phone_not_empty);
            return;
        }
        if (oldbirthday == null || oldbirthday.length() < 2) {
            okiv.setEnabled(true);
            ToastUtil.showMessage(this, R.string.old_brithday_not_empty);
            return;
        }
        // 添加老人
        authorization = (String) SPUtils.get(this, "authorization", "");
        Map<String, String> param = new HashMap<String, String>();
        param.put("name", oldname + "");
        param.put("sex", usersex + "");
        param.put("phone", oldphone + "");
        param.put("birthday", oldbirthday + "");
        param.put("egcontact", egcontact + "");
        param.put("egphone", egphone + "");
        param.put("headpic", userPicId + "");
        param.put("id", olderId + "");
        OkHttpTask.newInstance(this).post(param, OkType.form)
                .addHeader("authorization", authorization)
                .enqueue(new IOkTaskCallback() {
                    @Override
                    public void onSuccess(String result) {
                        if (result != null) {
                            Log.e("FZQ", "---" + result);
                            Gson gson = new Gson();
                            AddOlderJsonBean baseJsonBean = gson.fromJson(
                                    result, AddOlderJsonBean.class);
                            if (baseJsonBean.isStatus()) {
                                //假如添加了房间床位则绑定床位
                                ToastUtil.showMessage(FamilyEditOlderActivity.this,"修改成功");
                                SPUtils.put(FamilyEditOlderActivity.this,"addOldFlag",true);
                                back();
                            } else {
                                okiv.setEnabled(true);
                                ToastUtil.showMessage(getApplicationContext(),
                                        baseJsonBean.getMessage());
                            }
                        }
                    }
                }).start(UrlBean.OLDERUPDATEURL);
    }

    protected void back() {
        Intent intent = new Intent();
        setResult(0x55, intent);
        finish();
    }

    @Override
    public void initData() {
        super.initData();
        initSexPop();
        olderId = getIntent().getStringExtra("olderId");
        calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        //查询单个老人信息
        authorization = (String) SPUtils.get(this, "authorization", "");
        Map<String, String> param = new HashMap<String, String>();
        param.put("id", olderId + "");
        OkHttpTask.newInstance(this).post(param, OkType.form)
                .addHeader("authorization", authorization)
                .enqueue(new IOkTaskCallback() {
                    @Override
                    public void onSuccess(String result) {
                        if (result != null) {
                            Gson gson = new Gson();
                            SearchOlderInfoJsonBean oldersonBean = gson.fromJson(
                                    result, SearchOlderInfoJsonBean.class);
                            if (oldersonBean.isStatus()) {
                                if (oldersonBean.getData() != null) {
                                    controlData(oldersonBean.getData());
                                }
                            } else {
                                ToastUtil.showMessage(FamilyEditOlderActivity.this, oldersonBean.getMessage());
                            }
                        }
                    }
                }).start(UrlBean.OLDERSHOWURL);

    }

    private void controlData(SearchOlderInfoJsonBean.SearchOlderInfoDataBean oldersonBean) {
        userPicId = oldersonBean.getHeadPic();
        Glide.with(this).load(oldersonBean.getHeadpicture()).into(headiv);
        nameet.setText(oldersonBean.getName());

        if (oldersonBean.getPhone() != null) {
            phoneet.setText(oldersonBean.getPhone());
        }
        if (oldersonBean.getBirthday() != null) {
            birdaytv.setText(oldersonBean.getBirthday());
            oldbirthday = oldersonBean.getBirthday();
            String[] birss = oldersonBean.getBirthday().split("-");
            if (birss.length == 3) {
                year = Integer.valueOf(birss[0]);
                month = Integer.valueOf(birss[1]);
                day = Integer.valueOf(birss[2]);
            }
        }
        if (oldersonBean.getEgContact() != null) {
            egnameet.setText(oldersonBean.getEgContact());
        }
        if (oldersonBean.getEgPhone() != null) {
            egphoneet.setText(oldersonBean.getEgPhone());
        }

        usersex = "" + oldersonBean.getSex();
        if (usersex.equals("0")) {
            popsexrg.check(R.id.nursing_pop_sex_select_one_rb);
            sextv.setText(getString(R.string.man));
        } else {
            popsexrg.check(R.id.nursing_pop_sex_select_two_rb);
            sextv.setText(getString(R.string.woman));
        }

    }

    private class click implements OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.family_edit_older_ok_iv:
                    okiv.setEnabled(false);
                    olderAdd();
                    break;
                case R.id.family_editolder_sex_rl:
                    if (usersex.equals("0")) {
                        popsexrg.check(R.id.nursing_pop_sex_select_one_rb);
                    } else {
                        popsexrg.check(R.id.nursing_pop_sex_select_two_rb);
                    }
                    mPopupWindow.showAtLocation(v, Gravity.CENTER, 0, 0);
                    break;
                case R.id.family_editolder_head_iv:
                    choosePic();
                    break;
                case R.id.family_editolder_birday_tv:
                    chooseDay();
                    break;
                default:
                    break;
            }

        }
    }

    /**
     * 选择日期
     *
     * @param
     * @return void
     * @throws
     * @Description: TODO
     * @author fzq
     * @date 2017-10-11
     */
    private void chooseDay() {

        DatePickerDialog datePickerDialog = new DatePickerDialog(this,
                AlertDialog.THEME_HOLO_LIGHT, new OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int myear,
                                  int monthOfYear, int dayOfMonth) {
                /**
                 * 保存设置的时间
                 */
                oldbirthday = year + "-" + (monthOfYear + 1) + "-"
                        + dayOfMonth;
                year = myear;
                month = monthOfYear;
                day = dayOfMonth;
                oldbirthday = year + "-" + (monthOfYear + 1) + "-"
                        + dayOfMonth;
                birdaytv.setText(year + "-" + (monthOfYear + 1) + "-"
                        + dayOfMonth);

            }
        }, year, month, day);

        datePickerDialog.setCancelable(true);
        DatePicker dp = datePickerDialog.getDatePicker();
        dp.setMaxDate(calendar.getTimeInMillis());
        datePickerDialog.show();
    }

    /**
     * 拍照上传 相册选择
     *
     * @param
     * @return void
     * @throws
     * @Description: TODO
     * @author fzq
     * @date 2017-11-1
     */
    public void choosePic() {
        menuWindow = new SelectPicPopupWindow(this, itemsOnClick);
        menuWindow.showAtLocation(findViewById(R.id.family_editolder_head_iv),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    private boolean photoFlag;//拍照状态符
    private TakePictureManager takePictureManager;

    private OnClickListener itemsOnClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.takePhotoBtn:
                    autoObtainCameraPermission();
                    break;
                case R.id.pickPhotoBtn:
                    autoObtainStoragePermission();
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 自动获取相机权限
     */
    private void autoObtainCameraPermission() {

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
                Log.e("fzq", "您已经拒绝过一次");
            }
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, CAMERA_PERMISSIONS_REQUEST_CODE);
        } else {//有权限直接调用系统相机拍照
            if (hasSdcard()) {
                imageUri = Uri.fromFile(fileUri);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                    imageUri = FileProvider.getUriForFile(FamilyEditOlderActivity.this, "com.csun.nusing.fileprovider", fileUri);//通过FileProvider创建一个content类型的Uri
                PhotoUtils.takePicture(this, imageUri, CODE_CAMERA_REQUEST);
            } else {
                Log.e("fzq", "设备没有SD卡！");
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {
            case CAMERA_PERMISSIONS_REQUEST_CODE: {//调用系统相机申请拍照权限回调
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (hasSdcard()) {
                        imageUri = Uri.fromFile(fileUri);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                            imageUri = FileProvider.getUriForFile(FamilyEditOlderActivity.this, "com.csun.nusing.fileprovider", fileUri);//通过FileProvider创建一个content类型的Uri
                        PhotoUtils.takePicture(this, imageUri, CODE_CAMERA_REQUEST);
                    } else {
                        Log.e("fzq", "设备没有SD卡！");
                    }
                } else {
                    Log.e("fzq", "请允许打开相机！！");
                }
                break;


            }
            case STORAGE_PERMISSIONS_REQUEST_CODE://调用系统相册申请Sdcard权限回调
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    PhotoUtils.openPic(this, CODE_GALLERY_REQUEST);
                } else {

                    Log.e("fzq", "请允许打操作SDCard！！");
                }
                break;
        }
    }

    private int output_X = 480;
    private int output_Y = 480;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CODE_CAMERA_REQUEST://拍照完成回调
                    cropImageUri = Uri.fromFile(fileCropUri);
                    PhotoUtils.cropImageUri(this, imageUri, cropImageUri, 1, 1, output_X, output_Y, CODE_RESULT_REQUEST);
                    break;
                case CODE_GALLERY_REQUEST://访问相册完成回调
                    if (hasSdcard()) {
                        cropImageUri = Uri.fromFile(fileCropUri);
                        Uri newUri = Uri.parse(PhotoUtils.getPath(this, data.getData()));
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                            newUri = FileProvider.getUriForFile(this, "com.csun.nusing.fileprovider", new File(newUri.getPath()));
                        PhotoUtils.cropImageUri(this, newUri, cropImageUri, 1, 1, output_X, output_Y, CODE_RESULT_REQUEST);
                    } else {
                        Log.e("fzq", "设备没有SD卡！");
                    }
                    break;
                case CODE_RESULT_REQUEST:
                    Bitmap bitmap = PhotoUtils.getBitmapFromUri(cropImageUri, this);
                    urlpath = cropImageUri.getPath();
                    Log.e("fzq", "------" + urlpath);
                    postphoto(urlpath);
                    if (bitmap != null) {
                        showImages(bitmap);
                    }
                    break;
            }
        }
    }


    /**
     * 自动获取sdk权限
     */

    private void autoObtainStoragePermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSIONS_REQUEST_CODE);
        } else {
            PhotoUtils.openPic(this, CODE_GALLERY_REQUEST);
        }

    }

    private void showImages(Bitmap bitmap) {
        headiv.setImageBitmap(bitmap);
    }

    /**
     * 检查设备是否存在SDCard的工具方法
     */
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        return state.equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * 上传图片
     *
     * @param @param filePath
     * @return void
     * @throws
     * @Description: TODO
     * @author fzq
     * @date 2017-11-1
     */
    private void postphoto(String filePath) {
        File file = new File(filePath);
        authorization = (String) SPUtils.get(this, "authorization", "");
        MultipartBody.Builder requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);
        RequestBody body = RequestBody.create(MediaType.parse("image/*"), file);
        String filename = file.getName();
        requestBody.addFormDataPart("file", filename, body);
        requestBody.addFormDataPart("fileDesc", "头像");
        Request request = new Request.Builder()
                .addHeader("authorization", authorization)
                .url(UrlBean.FILEPOSTURL).post(requestBody.build()).tag(this)
                .build();
        OkHttpTask.newinstance(this).newBuilder()
                .readTimeout(20000, TimeUnit.MILLISECONDS).build()
                .newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("fzq", "onFailure");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.showMessage(getApplicationContext(),
                                "上传失败");
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response)
                    throws IOException {
                if (response.isSuccessful()) {
                    Gson gson = new Gson();
                    bean = gson.fromJson(response.body().string(),
                            FilePostJsonBean.class);
                    if (bean.getData() != null
                            && bean.getData().size() != 0) {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                userPicId = ""
                                        + bean.getData().get(0)
                                        .getResourceid();
                                userPic = ""
                                        + bean.getData().get(0)
                                        .getResourcepath();
                                ToastUtil.showMessage(
                                        getApplicationContext(),
                                        bean.getMessage());
                            }
                        });
                    }
                }
            }
        });
    }

}
